package restless.core {
	import restless.core.gameObjs.RLEUpdateRenderObj;
	import restless.core.interfaces.ICreateTimers;
	import restless.core.interfaces.ITimer;
	import restless.core.interfaces.IUR;
	import restless.core.managers.RLETimerManager;
	
	/**
	 * ...
	 * @author Jordan Laine
	 */
	
	public class RLETickTimer extends RLEUpdateRenderObj implements ITimer {
		
		private var _tickCount:int = 0;
		private var _tickTotal:int;
		private var _obj:ICreateTimers;
		private var _manualDispose:Boolean;
		private var _run:Boolean = true;
		private var _loop:Boolean;
		private var timeM:RLETimerManager;
		
		public function RLETickTimer(id:String, tickTotal:int, obj:ICreateTimers, TM:RLETimerManager, loop:Boolean = false, manualDispose:Boolean = false):void {
			init(id, tickTotal, obj, TM, loop, manualDispose);
		}
		
		public function init(id:String, tickTotal:int, obj:ICreateTimers, TM:RLETimerManager, loop:Boolean = false, manualDispose:Boolean = false):void {
			sID = id;
			_tickTotal = tickTotal;
			_obj = obj;
			_manualDispose = manualDispose;
			_loop = loop;
			timeM = TM;
		}
		
		public function get obj():ICreateTimers {
			return _obj;
		}
		
		public function resetTime():void {
			_tickCount = 0;
		}
		
		public function get time():int {
			return _tickTotal;
		}
		
		public function set time(num:int):void {
			_tickTotal = num;
		}
		
		public function set run(bool:Boolean):void {
			_run = bool;
		}
		
		public function get run():Boolean {
			return _run;
		}
		
		public function start():void {
			if (!_run) {
				_run = true;
			} else {
				trace (sID + " Timer is allready running");
			}
		}
		
		public function stop():void {
			if (_run) {
				_run = false;
			} else {
				trace (sID + " Timer is allready paused");
			}
		}
		
		public function set loop(bool:Boolean):void {
			_loop = bool;
		}
		
		override public function render():void {
			if (_run) {
				_tickCount++;
				if (_tickCount >= _tickTotal) {
					_obj.executeTimer(sID);
					if (!_loop) {
						_run = false;
						if (!_manualDispose) {
							dispose();
						}
					} else {
						_tickCount = 0;
					}
				}
			}
		}
		
		override public function dispose():void {
			if (_obj != null) {
				_obj.removeTimer(this);
				timeM.removeTimer(this);
				_obj = null;
				timeM = null;
			}
			super.dispose();
		}
	}
}